package com.ly.common;

import cn.hutool.core.util.StrUtil;
import com.gitee.fastmybatis.core.util.StringUtil;
import com.ly.dao.UserDao;
import com.ly.dao.UserTokenDao;
import com.ly.entity.User;
import com.ly.entity.UserToken;
import com.ly.exp.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class TokenHandler {

    private static UserDao staticUserDao;
    private static UserTokenDao staticUserTokenDao;
    @Resource
    private  UserDao userDao;
    @Resource
    private  UserTokenDao userTokenDao;

    @PostConstruct
    public void setDao(){
        staticUserDao = userDao;
        staticUserTokenDao = userTokenDao;
    }

    public  static User getUserInfo(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            throw new ServiceException(StatusEnum.UNAUTHORIZED.getCode(),"token过期,请重新登录");
        }
        UserToken userToken = staticUserTokenDao.selectByToken(token);
        if(Objects.isNull(userToken)){
            throw new ServiceException(StatusEnum.UNAUTHORIZED.getCode(),"token过期,请重新登录");
        }
        User user = staticUserDao.selectById(userToken.getUserId());
        if(Objects.isNull(user)){
            throw new ServiceException(StatusEnum.UNAUTHORIZED.getCode(),"用户不存在,请重新登录");
        }
        return user;
    }
}
